package com.mew.league.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mew.league.message.CommonResponse;
import com.mew.league.service.ILeagueService;
import com.mew.common.dc.mapper.LeagueMapper;
import com.mew.common.dc.mapper.MemberMapper;
import com.mew.common.entity.league.League;
import com.mew.common.entity.league.Member;
import com.mew.common.exception.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ztq
 * @since 2021-03-24
 */
@Service
public class LeagueServiceImpl extends ServiceImpl<LeagueMapper, League> implements ILeagueService {

    @Autowired
    private MemberMapper memberMapper;

    @Override
    @Transactional
    public CommonResponse createLeague(long uid, League league) {

        save(league);
        memberMapper.insertOrupdate(uid,league.getId(),1);
        return new CommonResponse();
    }

    public List<League> getLeagues(String name){
        return getBaseMapper().getLeagues(name);
    }

    /**
     * 申请联盟
     * @return
     */
    @Override
    public CommonResponse applicant(long uid,int leagueId) {
        //是否有联盟
        Member member = memberMapper.selectById(uid);
        if (inLeague(uid)){
            return new CommonResponse().buildByResponseCode(ResponseCode.InLeague);
        }

        //有没有
        QueryWrapper<League> eq = new QueryWrapper<League>().eq("id", leagueId).eq("state", 1);
        List<League> leagues = list(eq);
        if (leagues.isEmpty()||leagues.size()<1){
            return new CommonResponse().buildByResponseCode(ResponseCode.NoLeague);
        }
        League league = leagues.get(0);

        //公会满员
        if (league.getNumPeo()>19){
            return new CommonResponse().buildByResponseCode(ResponseCode.FullLeague);
        }

        //vip等级是否够
        Integer lowestVip = league.getLowestVip();

        //加入模式
        if (league.getJoinMode()==0){
            //自由加入
            //加入
            memberMapper.insertOrupdate(uid,leagueId,0);
            //全员推送

        }else {
            //申请
            //给会长发消息

        }


        return new CommonResponse();
    }


    @Override
    public boolean inLeague(long uid) {
        //是否有联盟
        Member byId = memberMapper.selectById(uid);
        if (null!=byId&&byId.getLeagueId()!=null&&byId.getLeagueId()!=0){
            //有
            return true;
        }
        return false;
    }
}
